package calao;

import java.io.File;
import java.net.URL;

import com.google.gwt.dev.GWTShell;
import com.google.gwt.dev.BootStrapPlatform;

public class DesktopTester {
	
	final Server server;
	final GWTShell shell = new GWTShell();
	final DesktopServlet servlet;
	
	String url = "/";
	
	public DesktopTester(Server server)
	{
		this.server = server;
		shell.setOutDir(server.config.desktopsDir);
		shell.setRunTomcat(false);
		shell.setPort(server.config.port);
		servlet = new DesktopServlet() {
			@Override
			protected URL getDesktopResource(File desktop, String path)
			{
				URL hit = null;
				for (Application app : getServer().getApplications()) {
					hit = getResource(app.getName(), path);
					if (hit!=null) return hit;
				}
				hit = getResource("calao", path);
				if (hit!=null) return hit;
				return super.getDesktopResource(desktop, path); 
			}	
			URL getResource(String packageName, String path) {
				String rpath = packageName.replace('.', '/') + "/public" + path;
				return Thread.currentThread().getContextClassLoader().getResource(rpath);
			}
		};
		server.add(servlet, "/");
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				DesktopTester.this.server.stop();
			}
		});
	}

	public void setDefaultDesktop(String desktop)
	{
		servlet.setDefaultDesktop(desktop);		
	}
	
	public void run()
	{
		shell.addStartupURL(url);
		server.start();
		BootStrapPlatform.go();
		shell.run();
	}
	
	public static void main(String[] argv) 
	throws InstantiationException, IllegalAccessException, ClassNotFoundException
	{
		// create a specific server configuration
		ServerConfig config = new ServerConfig();
		String url = null;
		for (int i=0; i<argv.length; i++) {
			if (argv[i].equals("-url")) url = argv[++i];
			else config.parseArg(argv[i], argv[++i]);
		}
		Server server = new Server(config);
		// create the tester and run it !
		DesktopTester tester = new DesktopTester(server);
		if (url!=null) tester.url = url;
		tester.run();
	    /*
	     * NOTE: main always exits with a call to System.exit to terminate any
	     * non-daemon threads that were started in Generators. Typically, this is to
	     * shutdown AWT related threads, since the contract for their termination is
	     * still implementation-dependent.
	     */
		System.exit(0);
	}
	
	public Server getServer()
	{
		return server;
	}
	
}
